package com.hsy.sunflowerbao.base.action

import com.flux.action.RxActionCreator
import com.flux.action.SubscriptionManager
import com.flux.dispatcher.Dispatcher
import com.flux.utils.LogUtil
import com.hsy.sunflowerbao.R
import com.hsy.sunflowerbao.utils.CommonUtils
import retrofit2.HttpException

/**
 * 基础行为构造器
 * Created on 2017/12/5.
 *
 * @author Yang
 */
open class BaseActionCreator(dispatcher: Dispatcher, manager: SubscriptionManager) : RxActionCreator(dispatcher, manager) {

    /**
     * 网络异常统一处理
     */
    protected fun handleHttpError(throwable: Throwable) {
        when (throwable) {
            is HttpException -> {
                LogUtil.d("HttpException")
                if (CommonUtils.isAuthDialogShowing) return

                val msg = when (throwable.code()) {
                    400 -> R.string.msg_param_lacked
                    401 -> R.string.msg_auth_failure
                    404 -> R.string.msg_invalid_request
                    405 -> R.string.msg_param_send_on_a_wrong_way
                    500 -> R.string.msg_internal_server_error
                    else -> R.string.txt_network_fail
                }

                val action = newAction(ActionType.HTTP_ERROR)
                action.data[Key.HTTP_ERROR_MSG_RES] = msg
                action.data[Key.NEED_LOGIN] = throwable.code() == 401
                postRxAction(action)
            }
            is HttpError -> {
                val action = newAction(ActionType.HTTP_ERROR)
                action.data[Key.HTTP_ERROR_MSG] = throwable.message
                action.data[Key.NEED_LOGIN] = false
                postRxAction(action)
            }
            else -> throwable.printStackTrace()
        }
    }

    /**
     * 检查网络请求结果
     */
    protected fun checkResult(status: String?, checked: String, msg: String?): Boolean {
        if (status != checked) {
            throw HttpError(msg)
        }
        return status == checked
    }
}